package eu.expressis.eiaf.auth.domain.service;

import java.util.List;

import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.acegisecurity.userdetails.jdbc.JdbcDaoImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;

import eu.expressis.eiaf.auth.domain.CustomUser;
import eu.expressis.eiaf.auth.infrastructure.integration.db.dao.UserDAO;

public class EiafUserDetailsService extends JdbcDaoImpl {

  @Autowired
  private UserDAO userDAO;

  private String[] userInfoObjectTypes;

  @Override
  public UserDetails loadUserByUsername(String username) {
    try {
      UserDetails user = super.loadUserByUsername(username);
      for(int i = 0; i < userInfoObjectTypes.length; i++) {
        List<Object> userInfos = userDAO
            .find("from " + userInfoObjectTypes[i] + " where username = '" + username + "'");
        if (userInfos != null) {
          Object userInfo = userInfos.get(0);
          if (userInfo != null)
            return new CustomUser(user.getUsername(), user.getPassword(), user.isEnabled(), user.getAuthorities(),
                userInfo);
        }
      }
      return new CustomUser(user.getUsername(), user.getPassword(), user.isEnabled(), user.getAuthorities());
    } catch (UsernameNotFoundException ex1) {
      ex1.printStackTrace();
      throw ex1;
    } catch (DataAccessException ex2) {
      ex2.printStackTrace();
      throw ex2;
    }
  }

  // public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException, DataAccessException {
  // User user = null;
  // GrantedAuthority[] grantedAuthorities = null;
  // try {
  // user = super.loadUserByUsername(userId);
  //
  // if (user == null) {
  // throw new UsernameNotFoundException("Invalid User");
  // }
  //
  // Set roles = user.getRoles();
  // int i = 0;
  // grantedAuthorities = new GrantedAuthority[roles.size()];
  // for(Iterator iter = roles.iterator(); iter.hasNext(); i++) {
  // Role role = (Role) iter.next();
  //
  // GrantedAuthority authority = new GrantedAuthorityImpl(role.getRole());
  // grantedAuthorities[i] = authority;
  // }
  // } catch (DataStoreException e) {
  // throw new DataRetrievalFailureException("Cannot loadUserByUsername userId:" + userId + " Exception:"
  // + e.getMessage(), e);
  // }
  //
  // UserDetails userDetails = new org.acegisecurity.userdetails.User(user.getUserId(), user.getPassword(),
  // user.isEnabled(), // enabled
  // user.isEnabled(), // accountNonExpired
  // user.isEnabled(), // credentialsNonExpired
  // user.isEnabled(), // accountNonLocked
  // grantedAuthorities);
  // return userDetails;
  // }

  public void setUserInfoObjectTypes(String[] userInfoObjectTypes) {
    this.userInfoObjectTypes = userInfoObjectTypes;
  }
}
